package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;
import cn.com.kh.signUtil;
import cn.com.kh.AESUtil;


import org.json.JSONArray;
import org.json.JSONException;

import org.json.JSONObject;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.parser.Feature;;

/**
 *
 * @Title: ApiBPQueryWO
 * @Description:深圳宝安排水小程序查询案件历史接口--外部接口
 * @author: chieh
 * @date 2020-11-11 21:28:00
 *
 */
public class ApiBPQueryWO implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(ApiBPQueryWO.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		
		log.debug("-------------------------start ApiBPQueryWO 开始-----------------");
		
		long startTime = System.currentTimeMillis();
		String reJson = null;
		long endTime = 0;
		
		response.setContentType("application/json;charset=utf-8");
		
		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}
		
		try {
			// 调用处理信息
			//JSONObject inObject = JSONObject.parseObject(inData, Feature.OrderedField);
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());
			
			// openid pagenum  pagesize 排序问题
			JSONArray jsonArraytemp = new JSONArray(inObject.get("data").toString());
			log.debug("jsonArraytemp: " + jsonArraytemp);
			
			JSONObject dataObjecttemp = jsonArraytemp.getJSONObject(0);
			log.debug(dataObjecttemp);
			String openidtemp = GetJV(dataObjecttemp, "openid");
			String pagenumtemp = GetJV(dataObjecttemp, "pagenum");
			String pagesizetemp = GetJV(dataObjecttemp, "pagesize");
			log.debug("openid:"+openidtemp+"	,pagenum:"+pagenumtemp+"	,pagesize:"+pagesizetemp);
			
			String replaceString ="[{\"openid\":\""+openidtemp+"\",\"pagenum\":"+pagenumtemp+",\"pagesize\":"+pagesizetemp+"}]";
			log.debug("replaceString:"+replaceString);
			
			//鉴权加密处理--验证密码
			JSONObject checkJson = signUtil.CheckSign(inObject,replaceString);
			log.debug("checkJson: " + checkJson);

			if (checkJson != null) {
				log.debug("[签名校验异常-返回信息]:" + checkJson);
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败([签名校验异常-返回信息]:"+signUtil.jsonObjectToMap(checkJson)+"),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
				return reJson;
			} else {
				log.debug("[签名校验成功]");
				// 校验成功
				//todo 业务逻辑
			}
			//data获取参数openid
			JSONArray jsonArray = new JSONArray(inObject.get("data").toString());
			log.debug("jsonArray: " + jsonArray);
			def openid= jsonArray.getJSONObject(0).get("openid");
			String pagenum= jsonArray.getJSONObject(0).get("pagenum");//当前页
			String pagesize= jsonArray.getJSONObject(0).get("pagesize");//每页大小
			
			log.debug("解析信息-openid：" + openid+"	pagenum" + pagenum+"	pagesize" + pagesize);
			
			String companytpye = "";
			String business1 = "";
			String business2 = "";
			String business3 = "";
			String isstreet = "";
			String address = "";
			String description = "";
			String locationx = "";
			String locationy = "";
			String status = "";
			String handleresult = "";
			String url = "";
			String filename = "";
			
			JSONArray resArray = new JSONArray();
			JSONObject resObject;
				
		
			if (openid == null||openid == "") {
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(phone必填字段;),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
				return reJson;
			}
			def customerresult = eliteBean.chaxun_sql("select top 1 CUSTOMER_GUID from CUSTOMER  where wechatid='"+openid+"' ORDER BY CREATEDDATE asc", "dataSource");
			log.debug("查看客户是否存在sql结果:" + customerresult);
			String old_customer_guid = null;
			if(customerresult.size() > 0) {
				old_customer_guid = customerresult.get(0).get("CUSTOMER_GUID");
				log.debug("old_customer_guid" + old_customer_guid);
				
				def listcountresult =eliteBean.chaxun_sql("SELECT 	objective_guid AS objective_guid FROM (SELECT o.objective_guid AS objective_guid,ROW_NUMBER () OVER (ORDER BY o.createddate desc) AS RowId FROM objective o LEFT JOIN TABCCONSULTWORKORDER t  on t.RELATION_ID=objective_guid LEFT JOIN customer c on o.customer_guid =c.customer_guid  WHERE	t.business_source = '3E98AF' and wechatid='"+openid+"') as a where a.RowId between ('"+pagenum+"'+0-1)*('"+pagesize+"'+0) and ('"+pagenum+"'+0)*('"+pagesize+"'+0)","dataSource");
				String objective_guid = null;
				int count=listcountresult.size();
				if(count > 0) {
					log.debug("历史案件存在一个以上！"+count);
					for (int i = 0; i <count; i++) {
						objective_guid = listcountresult.get(i).get("objective_guid");
						log.debug("objective_guid:" + objective_guid);
						def listresult =eliteBean.chaxun_sql("SELECT	isnull(o.workorderid,'') AS companytpye,	isnull(c2.callnaturegroupdescription,'') AS business1,	isnull(c3.callnaturedescription,'') AS business2,	isnull(c4.callnature3description,'') AS business3,	isnull(c5.Code_Name,'') AS isstreet,	isnull(t.address,'') AS address,	isnull(t.description,'') AS description,	isnull(t.location_x,'') AS locationx,	isnull(location_y,'') AS locationy,case when o.objectivestatus = 'OPEN' then '处理中' when o.objectivestatus = 'CLOSE' then '已完成' end AS status,isnull(case when t.handledescription='' or t.handledescription is null then o.comments else t.handledescription end, '') AS handleresult FROM objective o LEFT JOIN TABCCONSULTWORKORDER t  on t.RELATION_ID=objective_guid LEFT JOIN c_codetables c1 on c1.code_id=t.company_tpye and c1.Use_Type='单位类别'  LEFT JOIN callnaturegroup c2 on c2.callnaturegroup_id=t.business_type_1 LEFT JOIN callnature c3 on c3.callnature_id=t.business_type_2 LEFT JOIN callnature3 c4 on c4.callnature3_id=t.business_type_3 LEFT JOIN c_codetables c5 on c5.code_id=t.isstreet and c5.Use_Type='街道' WHERE	t.business_source = '3E98AF' and o.objective_guid='"+objective_guid+"'","dataSource");
						log.debug("SQL获取数据:"+listresult);
						if(listresult.size()>0) {
							companytpye = listresult.get(0).get("companytpye");
							business1 = listresult.get(0).get("business1");
							business2 = listresult.get(0).get("business2");
							business3 = listresult.get(0).get("business3");
							isstreet = listresult.get(0).get("isstreet");
							address = listresult.get(0).get("address");
							description = listresult.get(0).get("description");
							locationx = listresult.get(0).get("locationx");
							locationy = listresult.get(0).get("locationy");
							status = listresult.get(0).get("status");
							handleresult = listresult.get(0).get("handleresult");
							
							List urlresult =new ArrayList();
							urlresult =eliteBean.chaxun_sql("select rm.path as url from  rm_uploadrecord rm  where rm.objectiveID='"+objective_guid+"' and rm.type in ('4','5')","dataSource");
							//获取总行数
							def urllistsize =urlresult.size();
							log.debug("sql获取总条数:"+urllistsize);
							JSONArray urlresArray = new JSONArray();
							JSONObject urlresObject;
							String urlpath = "";
							for (int m = 0; m < urllistsize; m++) {
								urlresObject = new JSONObject();
								urlpath = urlresult.get(m).get("url");
								log.debug("urlpath:" + urlpath);
								if(urlpath==null) {
									urlpath="";
								}
								
								urlresObject.put("url", urlpath);
								urlresArray.put(urlresObject);
							}
							log.debug("urlresArray："+urlresArray);
							//def reJoson = Util.getJsonFromList(urlresult);
							//log.debug("reJoson："+reJoson);
							
							resObject = new JSONObject();
							resObject.put("companytpye", companytpye);
							resObject.put("business1", business1);
							resObject.put("business2", business2);
							resObject.put("business3", business3);
							resObject.put("isstreet", isstreet);
							resObject.put("address", address);
							resObject.put("description", description);
							resObject.put("locationx", locationx);
							resObject.put("locationy", locationy);
							resObject.put("status", status);
							resObject.put("handleresult", handleresult);
							resObject.put("arr",urlresArray);
							log.debug("resObject："+resObject);
							
							log.debug("resObject："+resObject);
							resArray.put(resObject);
							log.debug("resArray"+resArray);

						}
					}
					endTime = System.currentTimeMillis();
					reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"查询接口调用成功,调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":["+resArray.toString()+"]}";
				}else{
					endTime = System.currentTimeMillis();
					reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"查询接口调用成功(无客户相关案件),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
					return reJson;
				}
			}else{
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"查询接口调用成功(无客户相关案件),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
				return reJson;
			}
		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"查询接口调用处理失败(" + e.getMessage() + ")\",\"data\":[]}";

		}
		return reJson;

	}
	
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
}